package com.ruoyi.business.ajax;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.ajax.request.NotifyRequest;
import com.ruoyi.business.ajax.request.NotifyResource;
import com.ruoyi.business.ajax.request.ZfbNotifyRequest;
import com.ruoyi.business.domain.BizOrder;
import com.ruoyi.business.domain.BizPayOrder;
import com.ruoyi.business.service.IBizPayOrderService;
import com.ruoyi.business.utils.PayUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.framework.util.LogUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 微信支付回调
 * @author ruoyi
 */
@RestController
@RequestMapping("/ajax")
public class AjaxNotifyController extends BaseController {

    @Resource
    private IBizPayOrderService bizPayOrderService;

    @PostMapping("/wxNotify")
    public Map wxNotify(HttpServletRequest servletRequest) {
        //判断来源是微信平台
        String body = PayUtil.ReadAsChars(servletRequest);
        NotifyRequest request = JSON.parseObject(body, NotifyRequest.class);
        if (!PayUtil.checkWxRequest(servletRequest, body)) {
            LogUtils.getAccessLog().error("======微信回调请求来源不正确 body:" + body);
            return getWxResultMap("ERROR", "请求来源不正确");
        }

        if (!"TRANSACTION.SUCCESS".equals(request.getEvent_type())) {
            return getWxResultMap("ERROR", "支付未成功");
        }
        String code = "SUCCESS";
        String message = "";
        NotifyResource resource = request.getResource();
        String bodyStr = null;
        try {
            bodyStr = PayUtil.decryptBodyString(resource.getAssociated_data(), resource.getNonce(), resource.getCiphertext());
            LogUtils.getAccessLog().error("======微信回调解密包体 body:" + bodyStr);
        } catch (Exception e) {
            LogUtils.getAccessLog().error("======微信回调解密失败 body:" + body);
            e.printStackTrace();
        }
        if (bodyStr == null) {
            return getWxResultMap("ERROR", "数据解密失败");
        }
        JSONObject bodyObj = JSON.parseObject(bodyStr);
        if (!"SUCCESS".equals(bodyObj.getString("trade_state"))) {
            return getWxResultMap("ERROR", "支付未成功");
        }
        String transId = bodyObj.getString("transaction_id");
        String tradeNo = bodyObj.getString("out_trade_no");
        BizPayOrder order = bizPayOrderService.selectBizPayOrderByTradeNo(tradeNo);
        if (order == null || order.getTradeState() != 0) {
            LogUtils.getAccessLog().error("======微信回调商户订单数据不正确 tradeNo:" + tradeNo);
            return getWxResultMap("ERROR", "商户订单数据不正确");
        }
        //long amount = bodyObj.getJSONObject("amount").getLong("total");
        long amount = bodyObj.getJSONObject("amount").getLong("total") / 100;
        //测试用1分钱
        if (amount != order.getTradeNum().longValue()) {
            LogUtils.getAccessLog().error("======微信回调商户订单价格不正确 tradeNo:" + tradeNo + " amount:" + amount);
            return getWxResultMap("ERROR", "商户订单价格不正确");
        }
        order.setTradeState(1);
        order.setTransactionId(transId);
        try {
            bizPayOrderService.notifyPayOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
            code = "ERROR";
            message = "商户订单更新失败";
            LogUtils.getAccessLog().error("======微信回调商户订单更新失败 order:" + JSON.toJSONString(order));
        }
        return getWxResultMap(code, message);
    }

    @PostMapping("/zfbNotify")
    public String zfbNotify(ZfbNotifyRequest request, HttpServletRequest servletRequest) {
        if (!PayUtil.checkZfbRequest(request, servletRequest)) {
            LogUtils.getAccessLog().error("======支付宝回调请求来源不正确 body:" + JSON.toJSONString(request));
            return "error";
        }
        if (!"TRADE_SUCCESS".equals(request.getTrade_status())) {
            return "error";
        }

        String transId = request.getTrade_no();
        String tradeNo = request.getOut_trade_no();
        BizPayOrder order = bizPayOrderService.selectBizPayOrderByTradeNo(tradeNo);
        if (order == null || order.getTradeState() != 0) {
            LogUtils.getAccessLog().error("======支付宝回调商户订单数据不正确 tradeNo:" + tradeNo);
            return "error";
        }
        //long amount = (long) (100 * request.getTotal_amount());
        long amount = request.getTotal_amount().longValue();
        //测试用1分钱
        if (amount != order.getTradeNum().longValue()) {
            LogUtils.getAccessLog().error("======支付宝回调商户订单价格不正确 tradeNo:" + tradeNo + " amount:" + amount);
            return "error";
        }
        order.setTradeState(1);
        order.setTransactionId(transId);
        try {
            bizPayOrderService.notifyPayOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.getAccessLog().error("======支付宝回调商户订单更新失败 order:" + JSON.toJSONString(order));
            return "error";
        }
        return "success";
    }

    private Map getWxResultMap(String code, String message) {
        Map result = new HashMap<>();
        result.put("code", code);
        result.put("message", message);
        return result;
    }
}
